package chordcows;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

import de.uniba.wiai.lspi.chord.service.ServiceException;


public class FileUtility {
	
	private File fileDir;
	private File stub;
	private Hashtable<String,Integer> presentFiles;
	
	public FileUtility(String fileDir){
		
		if(fileDir==null)
			System.out.println("wtf");
		this.fileDir = new File(fileDir);
		presentFiles = new Hashtable<String,Integer>();
		
		stub=new File("src/chordcows/stub.sh.x");//TODO
	}
	
	public boolean createStubFile(String file){
		
		File newStub = new File(fileDir.getAbsolutePath()+"/"+file+".stub");
		copystub(newStub);
		return true;//TODO 
	}
	
	public void copystub(File newStub){
	    try{
	      
	      
	      InputStream in = new FileInputStream(stub);
	      OutputStream out = new FileOutputStream(newStub);

	      byte[] buf = new byte[1024];
	      int len;
	      while ((len = in.read(buf)) > 0){
	        out.write(buf, 0, len);
	      }
	      in.close();
	      out.close();
	      newStub.setExecutable(true,false);
	      
	    }catch(FileNotFoundException ex){
	        System.out.println(ex.getMessage() + " in the specified directory.");
	    }catch(IOException e){
	        System.out.println(e.getMessage());      
	    }
	}
	
	public String[] getAllLocalFiles(){
		String [] files = fileDir.list();
		for(int x=0; x<files.length; x++){
			if(files[x].endsWith(".stub")){
				files[x]= files[x].substring(0,files[x].indexOf(".stub"));
			}
		}
		System.out.println("getALL");
		for(String file: files)
			System.out.println(file);
		
		return files;
	}
	
	public String[] getRealFiles(){
		String [] files = fileDir.list();
		ArrayList<String> realFiles = new ArrayList<String>();
		for(String file: files){
			if(!file.endsWith(".stub")){
				realFiles.add(file);
			}
		}
		
		String[] temp = new String[realFiles.size()];
		return realFiles.toArray(temp);
	}
	
	public String[] checkForMissingFiles(){
		ArrayList<String> missing = new ArrayList<String>();
		ArrayList<String> localFiles = new ArrayList<String>(Arrays.asList(fileDir.list()));
		
		Iterator<String> iter = presentFiles.keySet().iterator(); 
		while(iter.hasNext()){
			String temp = iter.next();
			if(!localFiles.contains(temp))
				missing.add(temp);
		}
		//left over files in localFiles are missing from 
		String[] temp = new String[missing.size()];
		return missing.toArray(temp);
	}
	
	public void sync(Set<Serializable> master)throws ServiceException{
		System.out.println("syncing");
		presentFiles = new Hashtable<String,Integer>();//create anew for possible deletes?
		for(Serializable fileString: master)
			presentFiles.put((String)fileString,0);
		
		System.out.println("Syncing: Master size: " +presentFiles.size());
		
		if(presentFiles.size()==0)//ugh, need to build master
			throw new ServiceException("Dead Master File");
		
		String[] missing = checkForMissingFiles();
		
		for(String missingFile: missing)
			createStubFile(missingFile);
	}
	
	public boolean exists(String filename){
		File file = new File(fileDir.getAbsolutePath()+"/"+filename);
		return file.exists();
	}
	
	public String getFileDir(){
		return fileDir.getAbsolutePath();
	}
	
	public void setFileDir(String filepath){
		fileDir = new File(filepath);
	}

}
